package cc.ttiot.service.dataCollection.usb;

import org.bytedeco.javacpp.opencv_core;
import org.bytedeco.javacpp.opencv_imgcodecs;
import org.bytedeco.javacv.FrameGrabber;
import org.bytedeco.javacv.OpenCVFrameConverter;
import org.bytedeco.javacv.OpenCVFrameGrabber;


/**
 * @Description: TODO
 * @Author WangSuheng
 * @Date 2021/11/22 15:05
 * @Version 1.0
 */

//使用USB摄像头，javaCV读取图片并保存在本地 /home/pi/Pictures/door.png
public class PictureCollection {
    static OpenCVFrameConverter.ToIplImage converter = null;
    static OpenCVFrameGrabber grabber = null;
    private static int deviceNumber = 0;

    static {
        converter = new OpenCVFrameConverter.ToIplImage();
        init();
    }

    public boolean collect() throws FrameGrabber.Exception {
        opencv_core.Mat mat = converter.convertToMat(grabber.grabFrame());
        return opencv_imgcodecs.imwrite("/home/pi/ProtectiveDoor/door.png", mat);
    }

    public static void init() {
        while (true) {
            grabber = new OpenCVFrameGrabber(deviceNumber);
            try {
                //开始获取摄像头数据
                grabber.start();
                break;
            } catch (FrameGrabber.Exception e) {
                deviceNumber = (deviceNumber + 1) % 2;
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException interruptedException) {
                    interruptedException.printStackTrace();
                }
                e.printStackTrace();
            }
        }

    }
}
